import Vue from "vue";
import Vuex from "vuex";
import storage from "@/utils/storage";

Vue.use(Vuex);

const store = new Vuex.Store({
	state: {
		isShowToast: false, // 是否在展示Toast中
		remark: [], //填写订单备注
		shareLink: "", //分享链接
		verificationKey: "", //获取key表示验证通过
		distributionId: "", //分销员Id 如果当前账户从未登录过时记录
		hasLogin: storage.getHasLogin(),
		userInfo: storage.getUserInfo(),
		uuid: storage.getUuid(),
		token: "",
		tradesmanInfo: storage.getTradesmanInfo(),
		goods: {},
		count: 0, //未读通知数量
		chatUnreadCount: 0, //未读消息数量
		countInfo: [], //未读通知明细
		chatId: '', //当前打开的聊天页面
		circleInfo: {}, //当前编辑的帖子
		cartCount: 0, //购物车商品数量
	},

	mutations: {
		login(state, userInfo) {
			state.userInfo = userInfo || {};
			state.userName =
				userInfo.Name || userInfo.Nickname || userInfo.Username || "匿名用户";
			state.hasLogin = true;
		},
		// 更新用户信息
		updateUserInfo(state, userInfo) {
			state.userInfo = userInfo || {};
			state.userName =
				userInfo.Name || userInfo.Nickname || userInfo.Username || "匿名用户";
			// 触发全局用户信息更新事件
			uni.$emit('userInfoUpdated', userInfo);
		},
		logout(state) {
			state.userName = "";
			state.hasLogin = false;
			state.cartCount = 0; // 登出时清空购物车数量
		},
		//当前商品详情
		setGoodsItem(state, goods) {
			state.goods = goods
		},
		// 设置填写订单中备注
		setRemark(state, remark) {
			state.remark = remark;
		},
		SETUSERINFO(state, data) {
			state.userInfo = data;
		},
		SETCOUNT(state, data) {
			state.count = data;
		},
		setChatId(state, data) {
			state.chatId = data;
		},
		setChatUnreadCount(state, data) {
			state.chatUnreadCount = data;
		},
		incrementCartCount(state, increment) {
			state.cartCount = (state.cartCount || 0) + increment;
		},
		setCartCount(state, count) {
			state.cartCount = count || 0;
		},
		setEditCircle(state, data) {
			state.editCircle = data;
		}
	},
	actions: {},
	getters: {
		getUserInfo: state => state.userInfo,
		getCount: state => {
			const chatCount = state.chatUnreadCount || 0;
			const noticeCount = state.count || 0;
			return chatCount + noticeCount;
		},
		totalUnreadCount: state => {
			const chatCount = state.chatUnreadCount || 0;
			const noticeCount = state.count || 0;
			return chatCount + noticeCount;
		},
		getChatId: state => state.chatId,
		getChatUnreadCount: state => state.chatUnreadCount,
		getCartCount: state => state.cartCount || 0,
		getEditCircle: state => state.editCircle
	}
});

export default store;